package com.leyou.item.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.mapper.CategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author 虎哥
 */
@Service
public class CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    // SELECT * FROM tb_category WHERE parent_id = #{pid}
    public List<CategoryDTO> queryCategoryByParent(Long pid) {
        // 构建查询条件对象，这个对象中的非空字段，就会称为sql中的where 条件，多个字段，是and关系
        Category category = new Category();
        category.setParentId(pid);

        // 查询
        List<Category> list = categoryMapper.select(category);

        // 健壮性判断
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.RESOURCE_NOT_FOUND);
        }

        // 返回
        return BeanHelper.copyWithCollection(list, CategoryDTO.class);
    }

    public List<CategoryDTO> queryByIds(List<Long> ids){
        List<Category> list = categoryMapper.selectByIdList(ids);
        // 健壮性判断
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.RESOURCE_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, CategoryDTO.class);
    }
}
